package logic

import (
	"context"
	"encoding/json"
	"time"
	"zhihu/models/cathe"
	"zhihu/models/mysql"

	"zhihu/zhihurpc/internal/svc"
	"zhihu/zhihurpc/zhihurpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ProblemaTopListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewProblemaTopListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ProblemaTopListLogic {
	return &ProblemaTopListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ProblemaTopListLogic) ProblemaTopList(in *zhihurpc.ProblemaTopListRequest) (*zhihurpc.ProblemaTopListResponse, error) {
	// todo: add your logic here and delete this line
	var findProblm []mysql.Problem
	get := cathe.Rdb.Get(l.ctx, "problmTopList")

	if get.Val() != "" {
		json.Unmarshal([]byte(get.Val()), &findProblm)
	} else {
		mysql.DB.Debug().Order("hot desc").Find(&findProblm)
		marshal, _ := json.Marshal(findProblm)
		cathe.Rdb.Set(l.ctx, "problmTopList", marshal, time.Minute*10)
	}

	var ProblmList []*zhihurpc.ProblemaTopList

	for _, problem := range findProblm {
		list := zhihurpc.ProblemaTopList{
			Title:        problem.Title,
			ProblemImage: problem.ProblemImage,
			Hot:          int64(problem.Hot),
			UserId:       int64(problem.UserId),
			ProblemId:    int64(problem.ID),
		}
		ProblmList = append(ProblmList, &list)
	}

	return &zhihurpc.ProblemaTopListResponse{
		List: ProblmList,
	}, nil
}
